package com.example.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.api.dto.ResStatusCode;
import com.example.api.entity.Category;
import com.example.api.exception.CustomException;
import com.example.api.service.ICategoryService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 分类表 前端控制器
 * </p>
 *
 * @author xushuo
 * @since 2020-09-06
 */
@RestController
@RequestMapping("/api/category")
public class CategoryController {
    private static final Logger log = LoggerFactory.getLogger(CategoryController.class);


    @Autowired
    private ICategoryService categoryService;


    @GetMapping("/getCategories")
    @ApiOperation("获取分类列表接口")
    public ResponseEntity<List<Category>> getCategoryList(){

        try {
            QueryWrapper<Category> queryWrapper = new QueryWrapper();
            queryWrapper.eq("deleted",0)
                    .eq("level",1)
                    .orderByAsc("sorted");

            List<Category> categories = categoryService.list(queryWrapper);

            for (Category category : categories) {
                QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
                categoryQueryWrapper.eq("deleted",0)
                        .eq("level",2)
                        .eq("parent_id",category.getId())
                        .orderByAsc("sorted");

                //获取二级分类
                List<Category> subjectList = categoryService.list(categoryQueryWrapper);

                category.setSubjectList(subjectList);
            }

            return ResponseEntity.ok(categories);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
           throw  new CustomException("", ResStatusCode.CATEGORY_QUERY_ERROR.getCode(),ResStatusCode.CATEGORY_QUERY_ERROR.getMessage());
        }

    }






}
